<template>
  <RightTableLayout :slotName="['search', 'operation', 'table', 'pagination']">
    <template #search>
      <Query :columns="columns" @query="doQuery"></Query>
    </template>
    <template #operation>
      <el-button @click="add">
        <el-icon>
          <DocumentAdd />
        </el-icon>{{ i18n.fy.新增 }}</el-button>
    </template>
    <template #table>
      <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" border v-loading="data.loading"
        :element-loading-text="i18n.fy.loading">
        <el-table-column prop="" label="ID" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="rolename" :label="i18n.language === 'zh-cn' ? '角色名称' : 'rolename'" align="center" />
        <el-table-column prop="roledesc" :label="i18n.language === 'zh-cn' ? '角色备注' : 'roledesc'" align="center">
        </el-table-column>
        <el-table-column prop="available" :label="i18n.language === 'zh-cn' ? '是否可用' : 'available'" align="center">
          <template #default="scope">
            <span v-if="scope.row.available == '1'">
              {{ i18n.language === "zh-cn" ? "可用" : "available" }}
            </span>
            <span v-else> {{ i18n.language === "zh-cn" ? "不可用" : "Not Available" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="op" :label="i18n.language === 'zh-cn' ? '操作' : 'operate'" align="center">
          <template #default="scope">
            <a class="layui-btn layui-btn-xs" @click="edit(scope.row)"> {{ i18n.language === "zh-cn" ? "编辑" : "edit"
              }}</a>
            <a class="layui-btn layui-btn-warm layui-btn-xs" @click="selectRoleMenu(scope.row)"> {{ i18n.language ===
    "zh-cn" ? "分配菜单" : "assignmentsMenu" }}</a>
            <a class="layui-btn layui-btn-danger layui-btn-xs" @click="del(scope.row)"> {{ i18n.fy.删除 }}</a>
            <a v-if="enable" class="layui-btn layui-btn-xs" @click="assign(scope.row)">{{ i18n.fy.分配权限 }}</a>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <template #pagination>
      <el-pagination @size-change="onChanSize" @current-change="onChanPage" v-model:current-page="data.queryForm.page"
        v-model:page-size="data.queryForm.limit" :total="data.total" />
    </template>
  </RightTableLayout>
  <div id="saveOrUpdateDiv" style="display: none; padding: 20px">
    <form class="layui-form" lay-filter="dataFrm" id="dataFrm">
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "角色名称" : "RoleName" }}
          :</label>
        <div class="layui-input-block">
          <input type="hidden" name="roleid" />
          <input type="text" name="rolename"
            :placeholder="i18n.language === 'zh-cn' ? '请输入角色名称' : 'Please enter a role name'" autocomplete="off"
            class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">
          {{ i18n.language === "zh-cn" ? "角色备注" : "RoleNotes" }}
          :</label>
        <div class="layui-input-block">
          <input type="text" name="roledesc"
            :placeholder="i18n.language === 'zh-cn' ? '请输入角色备注' : 'Please enter a role comment'" autocomplete="off"
            class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-inline">
          <label class="layui-form-label">
            {{ i18n.language === "zh-cn" ? "是否可用" : "Isitavailable" }}
            :</label>
          <div class="layui-input-inline">
            <input type="radio" name="available" value="1" checked="checked"
              :title="i18n.language === 'zh-cn' ? '可用' : 'available'" />
            <input type="radio" name="available" value="0"
              :title="i18n.language === 'zh-cn' ? '不可用' : 'NotAvailable'" />
          </div>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: center; width: 100%">
        <div class="layui-input-block">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release"
            lay-filter="doSubmit" lay-submit="">
            {{ i18n.fy.提交 }}
          </button>
          <button type="reset" class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ i18n.fy.重置 }}
          </button>
        </div>
      </div>
    </form>
  </div>
  <div id="selectRoleMenu" style="display: none">
    <ul id="menuTree" class="dtree" data-id="0"></ul>
  </div>
  <el-dialog class="dialogPermiss" style="background: #000" v-model="dialogVisible" title="权限列表" width="25%"
    :before-close="handleClose" draggable>
    <div class="PermissionList">
      <el-table :empty-text="i18n.fy.nodata" :data="PermissionList" :element-loading-text="i18n.fy.loading" height="500"
        @selection-change="handleSelectionChange" ref="multipleTableRef">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="description" :label="i18n.language === 'zh-cn' ? '权限名称' : 'description'"
          align="center" />
      </el-table>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePermissionList"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
defineOptions({ name: "RoleList" });
import Query from "@/components/query.vue";
import RightTableLayout from "@/views/workbench/components/RightTableLayout.vue";
import { i18nStore } from "@/pinia/i18n";
const i18n = i18nStore();

const {
  appContext: {
    config: { globalProperties },
  },
} = getCurrentInstance();
let $httpUrl = globalProperties.$httpUrl;

let columns = reactive({
  rolename: { label: i18n.fy.角色名称, queryValue: "" },
  roledesc: { label: i18n.fy.角色备注, queryValue: "" },
  available: { type: "radio", label: i18n.fy.是否可用, queryValue: "" },
});

let data = reactive({
  queryForm: {
    page: 1,
    limit: 100,
  },
  tableData: [],
  total: 0,
  dialog: false,
  form: {},
  rules: {
    name: [{ required: true, message: "请输入姓名", trigger: "change" }],
    role: [{ required: true, message: "请选择岗位", trigger: "change" }],
  },
});

const reQueryForm = () => {
  // 重置查询表单
  data.queryForm = {
    page: 1,
    limit: 100,
  };
};

const currentChange = (page) => {
  pageData.queryForm.page = page;
  getList();
};

const sizeChange = (size) => {
  data.queryForm.page = size;
  getList();
};
let multipleTableRef = ref(null);
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTableRef.value.toggleRowSelection(row, undefined);
    });
  } else {
    multipleTableRef.value.clearSelection();
  }
};

const add = () => {
  // 新增
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "新增角色" : "Add Role",
    content: $("#saveOrUpdateDiv"),
    area: ["800px", "300px"],
    success: function (index) {
      //清空表单数据
      $("#dataFrm")[0].reset();
      $("input[name=available][value='1']").prop("checked", true);
      $("input[name=available][value='0']").prop("checked", false);
      url = $httpUrl + "/role/insertRole";
    },
  });
};
// 编辑
const edit = (data) => {
  mainIndex = layer.open({
    type: 1,
    title: i18n.language === "zh-cn" ? "修改用户" : "Modify Users",
    content: $("#saveOrUpdateDiv"),
    area: ["800px", "300px"],
    success: function (index) {
      form.val("dataFrm", data);
      url = $httpUrl + "/role/updateRole";
    },
  });
};
// 修改分页数
const onChanSize = (e) => {
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getList();
};
//修改分页
const onChanPage = (e) => {
  data.queryForm.page = e;
  getList();
};

const del = (data) => {
  // 删除
  layer.confirm((i18n.language === "zh-cn" ? "真的删除" : "Really delete") + "【" + data.rolename + "】" + (i18n.language === "zh-cn" ? "这个角色吗" : "Is this character"), function (index) {
    //向服务端发送删除指令
    $.post($httpUrl + "/role/deleteRole", { roleid: data.roleid }, function (res) {
      layer.msg(res.msg);
      //刷新数据 表格
      getList();
    });
  });
};

let formRef = ref(null);

const submit = () => {
  // 提交新增/编辑表单
  formRef.value.validate((valid) => {
    if (valid) {
    }
  });
};

const getList = (params) => {
  // 获取表格数据
  data.loading = true;
  $axios
    .get("/role/loadAllRole", {
      ...data.queryForm,
      ...params,
    })
    .then((res) => {
      data.loading = false;
      data.tableData = res.data.data.records;
      data.total = res.data.data.total;
    });
};

const doQuery = (params) => {
  getList(params);
};

const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
};

const selectRoleMenu = (data) => {
  openselectRoleMenu(data);
};
let PermissionList = ref([]);
let dialogVisible = ref(false);
let currentRow = {};
const assign = (row) => {
  currentRow = row;
  $axios.get("/role/getPermissionList", {}).then((res) => {
    let dataTable = res.data.data;
    $.post($httpUrl + "/role/getRolePermissions", { roleid: row.roleid }, function (res) {
      PermissionList.value = dataTable;
      if (res.data == null) {
        return false;
      }
      for (let i = 0; i < res.data.length; i++) {
        if (check(res.data[i].permission_id)) {
          window.setTimeout(function () {
            toggleSelection([check(res.data[i].permission_id)]);
          }, 300);
        }
      }
    });
  });
  dialogVisible.value = true;
};
let enable = ref(false);
const getRole = (id) => {
  $axios
    .post(`/role/getRole`)
    .then((res) => {
      for (const i of res.data.data) {
        if (i.role_key === "Admin") {
          enable.value = true;
          break;
        }
      }
    })
    .catch((err) => { });
};

const check = (id) => {
  let arr = PermissionList.value.filter((item) => {
    return id == item.permission_id;
  });
  if (arr.length > 0) {
    return arr[0];
  } else {
    return false;
  }
};
let multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
const handleClose = () => {
  dialogVisible.value = false;
};
const savePermissionList = (val) => {
  let params = { ids: "", roleid: currentRow.roleid };
  multipleSelection.value.map((item) => {
    params.ids = params.ids + item.permission_id + ",";
  });
  params.ids = params.ids.substring(0, params.ids.lastIndexOf(","));
  $.post($httpUrl + "/role/setRolePermission", params, function (res) {
    if (res.code == 200) {
      layer.msg("保存成功");
    } else {
      layer.msg(res.message);
    }
    dialogVisible.value = false;
  });
};
var tableIns;
var $ = "";
var layer = "";
var form = "";
var table = "";
var dtree = "";
var url = "";
var mainIndex = "";

var menuTree = "";
//打开分配菜单的弹出层
function openselectRoleMenu (data) {
  mainIndex = layer.open({
    type: 1,
    title: (i18n.language === "zh-cn" ? "分配" : "allocation") + "【" + data.rolename + "】" + (i18n.language === "zh-cn" ? "的角色" : "Role of"),
    content: $("#selectRoleMenu"),
    area: ["400px", "450px"],
    btnAlign: "c",
    btn: ['<div class="layui-icon layui-icon-release">' + (i18n.language === "zh-cn" ? "确认分配" : "Confirming") + "</div>", '<div class="layui-icon layui-icon-close">' + (i18n.language === "zh-cn" ? "取消分配" : "Unassign") + "</div>"],
    yes: function (index, layero) {
      var nodes = dtree.getCheckbarNodesParam("menuTree");
      var roleid = data.roleid;
      var params = "roleid=" + roleid;
      $.each(nodes, function (i, item) {
        params += "&ids=" + item.nodeId;
      });
      //保存角色和菜单的关系
      $.post($httpUrl + "/role/saveRoleMenu", params, function (res) {
        if ((res.code = 200)) {
          layer.msg(res.msg);
          //parent.layer.closeAll();
          //"#selectRoleMenu").hide();
          layer.close(mainIndex);
        } else {
          layer.msg(res.msg);
        }
      });
    },
    success: function (index) {
      //初始化树
      menuTree = dtree.render({
        elem: "#menuTree",
        dataStyle: "layuiStyle", //使用layui风格的数据格式
        response: { message: "msg", statusCode: 0 }, //修改response中返回数据的定义
        dataFormat: "list", //配置data的风格为list
        checkbar: true, //复选框
        checkbarType: "all", // 默认就是all
        checkbarData: "choose",
        url: $httpUrl + "/role/initRoleMenuTreeJson?roleid=" + data.roleid, // 使用url加载（可与data加载同时存在）
      });
    },
  });
}

onMounted(() => {
  getRole();
  layui
    .extend({
      dtree: "/layui_ext/dist/dtree",
    })
    .use(["jquery", "layer", "form", "table", "dtree"], function () {
      $ = layui.jquery;
      layer = layui.layer;
      form = layui.form;
      table = layui.table;
      dtree = layui.dtree;
      //保存
      form.on("submit(doSubmit)", function (obj) {
        //序列化表单数据
        var params = $("#dataFrm").serialize();
        $.post(url, params, function (res) {
          if ((res.code = 200)) {
            layer.msg(res.msg);
            layer.close(mainIndex);
            //刷新数据 表格
            // tableIns.reload();
            getList();
          } else {
            layer.msg(res.msg);
          }
        });
      });
    });

  getList({});
});
</script>

<style lang="scss" scoped>
.available1 {
  color: orangered;
}

#menuToolBar {
  display: flex;
  justify-content: left;
  align-items: left;
  flex: 1;
  padding-left: 20px;
}

:deep(.dialogPermiss .is-horizontal) {
  display: none !important;
}

:deep(.dialogPermiss .el-dialog__title) {
  color: #fff !important;
}

:deep(.PermissionList .el-table td.el-table__cell div) {
  color: #fff !important;
}

:deep(.PermissionList .el-table th .cell) {
  color: #fff !important;
  font-weight: bold;
}

:deep(.PermissionList .el-table td) {
  border-left: solid 1px #ccc !important;
  border-top: solid 1px #ccc !important;
  border-left: solid 1px #ccc !important;
}

:deep(.PermissionList .el-table th) {
  border-left: solid 1px #ccc !important;
  border-top: solid 1px #ccc !important;
  border-left: solid 1px #ccc !important;
}

:deep(.PermissionList .is-vertical .el-scrollbar__thumb) {
  background: #ccc !important;
}

:deep(.PermissionList .el-table__inner-wrapper) {
  border-right: solid 1px #ccc !important;
  overflow-x: hidden;
}

.dialog-footer {
  display: block;
  text-align: center;
}
</style>

<style>
.toLoadAllRole {
  display: flex !important;
}
</style>
